<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <div class="add-store-btn" @click="addNewStore" title="新增店铺">
        <i class="fa fa-plus-circle"></i>
        <span>新增</span>
      </div>
      <p>选择店铺</p>
      <div class="back-btn" @click="backToUserInfo" title="返回我的页面">
        <i class="fa fa-user"></i>
        <span>我的</span>
      </div>
    </header>

    <div class="page-content">
      <div class="title-section">
        <h2>您的账号关联了多个店铺</h2>
        <p>请选择要管理的店铺：</p>
      </div>

      <div class="stores-container">
        <div 
          v-for="store in stores" 
          :key="store.id" 
          class="store-card"
          @click="selectStore(store)"
        >
          <img :src="getBusinessImage(store.id)" alt="店铺图片" @error="handleImageError($event, store.id)">
          <div class="store-info">
            <h3>{{ store.businessName }}</h3>
            <p class="store-address">{{ store.businessAddress || '暂无地址信息' }}</p>
            <div class="store-stats">
              <span class="stat-item">
                <i class="fa fa-rmb"></i> 起送: {{ store.startPrice }}元
              </span>
              <span class="stat-item">
                <i class="fa fa-truck"></i> 配送: {{ store.deliveryPrice }}元
              </span>
            </div>
          </div>
          <i class="fa fa-angle-right"></i>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { imageApi } from '@/api';

// 辅助函数：检查商家是否被删除
const isBusinessDeleted = (business) => {
  // 检查所有可能的删除标记字段
  if (business.deleted === true) return true;
  if (business.isDeleted === true) return true;
  if (business.is_deleted === true) return true;
  if (business.isDeleted === 1) return true;
  if (business.is_deleted === 1) return true;
  
  // 如果没有明确标记为已删除，则认为未删除
  return false;
};

// 导入商家图片（作为备用）
import sj01 from '@/assets/sj01.png'
import sj02 from '@/assets/sj02.png'
import sj03 from '@/assets/sj03.png'
import sj04 from '@/assets/sj04.png'
import sj05 from '@/assets/sj05.png'
import sj06 from '@/assets/sj06.png'
import sj07 from '@/assets/sj07.png'
import sj08 from '@/assets/sj08.png'
import sj09 from '@/assets/sj09.png'

const router = useRouter();
const stores = ref([]);

// 获取商家图片
const getBusinessImage = (id) => {
  // 优先使用后端图片API获取商家上传的图片
  // 使用商家图片二进制数据API端点
  const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080';
  // 添加时间戳参数，避免浏览器缓存
  const timestamp = new Date().getTime();
  const backendImageUrl = `${apiBaseUrl}/api/images/business-binary/${id}?t=${timestamp}`;
  
  return backendImageUrl;
};

// 处理图片加载失败，使用预存的静态图片
const handleImageError = (event, businessId) => {
  console.warn(`商家图片加载失败，使用默认图片: businessId=${businessId}`);
  const images = {
    1: sj01, 2: sj02, 3: sj03, 4: sj04,
    5: sj05, 6: sj06, 7: sj07, 8: sj08, 9: sj09
  };
  
  // 根据商家ID取模获取图片
  const index = (businessId % Object.keys(images).length) + 1;
  event.target.src = images[index] || images[1];
};

// 选择店铺
const selectStore = (store) => {
  // 保存选中的店铺信息到localStorage
  localStorage.setItem("business", JSON.stringify(store));
  console.log("已选择店铺:", store.businessName);
  
  // 跳转到商家管理页面
  router.push({ path: '/businessManage' });
};

// 新增店铺
const addNewStore = () => {
  // 获取当前用户信息，检查是否具有商家权限
  const userInfoStr = localStorage.getItem("user-info");
  if (userInfoStr) {
    const userInfo = JSON.parse(userInfoStr);
    const authorities = userInfo.authorities || [];
    
    // 检查用户是否有BUSINESS权限
    const hasBusinessRole = authorities.some(auth => 
      auth.name === 'BUSINESS' || auth.name === 'ROLE_BUSINESS'
    );
    
    if (hasBusinessRole) {
      console.log("用户已有BUSINESS权限，直接跳转到商家注册第二步");
      // 设置标记，让商家注册页面直接跳到第二步
      localStorage.setItem('skip_to_step_two', 'true');
    } else {
      console.log("用户无BUSINESS权限，跳转到商家注册第一步进行身份验证");
      // 确保不设置skip_to_step_two标记
      localStorage.removeItem('skip_to_step_two');
    }
  } else {
    // 没有用户信息，确保不设置跳转标记
    localStorage.removeItem('skip_to_step_two');
  }
  
  // 跳转到商家注册页面
  router.push({ path: '/businessRegister' });
};

// 返回我的页面
const backToUserInfo = () => {
  router.push({ path: '/userInfo' });
};

// 页面初始化
onMounted(() => {
  // 获取当前登录用户信息
  const userInfoStr = localStorage.getItem("user-info");
  if (!userInfoStr) {
    alert("用户信息不存在，请重新登录");
    router.push({ path: '/businessLogin' });
    return;
  }
  
  const userInfo = JSON.parse(userInfoStr);
  console.log("当前登录用户ID:", userInfo.id);
  console.log("当前登录用户名:", userInfo.username);
  
  // 获取存储的商家列表
  const storesJson = localStorage.getItem("business_stores");
  if (storesJson) {
    // 解析存储的商家列表
    let businessStores = JSON.parse(storesJson);
    
    // 调试：输出第一个商家的完整数据结构
    if (businessStores.length > 0) {
      console.log('商家数据结构样例:', JSON.stringify(businessStores[0]));
    }
    
    // 再次确保过滤掉已删除的商家
    const filteredStores = businessStores.filter(store => {
      const isDeleted = isBusinessDeleted(store);
      
      // 如果是被删除的商家，打印信息
      if (isDeleted) {
        console.log(`过滤掉已删除商家: ${store.businessName}, ID: ${store.id}`);
      }
      
      return !isDeleted;
    });
    
    // 更新商家列表
    stores.value = filteredStores;
    console.log(`过滤后，加载了${stores.value.length}个未删除的商家`);
    
    // 打印商家名称列表便于调试
    if (stores.value.length > 0) {
      const storeNames = stores.value.map(store => store.businessName).join(', ');
      console.log("商家列表: " + storeNames);
    }
  } else {
    // 如果没有店铺列表，返回登录页
    alert("没有可选择的店铺信息");
    router.push({ path: '/businessLogin' });
    return;
  }
  
  // 如果只有一个店铺，直接选择
  if (stores.value.length === 1) {
    console.log("只有一个店铺，自动选择:", stores.value[0].businessName);
    selectStore(stores.value[0]);
  } else if (stores.value.length === 0) {
    alert("未找到与您账号关联的店铺");
    router.push({ path: '/businessLogin' });
  }
});
</script>

<style scoped>
.wrapper {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* header样式 */
header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.5vw;
  
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 4vw;
}

header .fa-sign-out {
  font-size: 5vw;
  cursor: pointer;
}

header .back-btn {
  display: flex;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 1vw 2.5vw;
  border-radius: 3vw;
  cursor: pointer;
  border: 1px solid rgba(255, 255, 255, 0.3);
  /* 通过调整以下属性控制按钮位置: */
  margin-right: 8vw; /*控制右侧间距*/
  /* margin-left: auto; 将按钮推到右侧最远处 */
  /* position: absolute; right: 10vw; 精确定位按钮 */
}

header .back-btn i {
  font-size: 4vw;
  margin-right: 1vw;
  /* 增加或减小图标大小 */
}

header .back-btn span {
  font-size: 3.5vw;
  font-weight: 500;
  /* 调整文字大小 */
}

/* 添加店铺按钮样式，与退出登录按钮一致 */
header .add-store-btn {
  display: flex;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 1vw 2.5vw;
  border-radius: 3vw;
  cursor: pointer;
  border: 1px solid rgba(255, 255, 255, 0.3);
  margin-left: 1vw;
}

header .add-store-btn i {
  font-size: 4vw;
  margin-right: 1vw;
  color: #fff;
}

header .add-store-btn span {
  font-size: 3.5vw;
  font-weight: 500;
}

.page-content {
  padding-top: 16vw;
  padding-bottom: 4vw;
}

.title-section {
  width: 90%;
  margin: 0 auto 4vw auto;
  text-align: center;
}

.title-section h2 {
  font-size: 5vw;
  color: #333;
  margin-bottom: 2vw;
}

.title-section p {
  font-size: 3.5vw;
  color: #666;
}

.stores-container {
  width: 92%;
  margin: 0 auto;
  box-sizing: border-box;
  overflow: hidden;
}

.store-card {
  width: 100%;
  background-color: #fff;
  border-radius: 3vw;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  margin-bottom: 4vw;
  padding: 3vw;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  box-sizing: border-box;
}

.store-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0,0,0,0.15);
}

.store-card img {
  width: 16vw;
  height: 16vw;
  border-radius: 2vw;
  object-fit: cover;
  flex-shrink: 0;
}

.store-info {
  flex: 1;
  padding: 0 3vw;
  overflow: hidden; /* 确保内容不会溢出 */
}

.store-info h3 {
  font-size: 4vw;
  color: #333;
  margin-bottom: 1vw;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.store-address {
  font-size: 3vw;
  color: #666;
  margin-bottom: 2vw;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 45vw; /* 减小最大宽度，确保在小屏幕上也不会溢出 */
}

.store-stats {
  display: flex;
  font-size: 3vw;
  color: #666;
}

.stat-item {
  margin-right: 3vw;
}

.stat-item i {
  margin-right: 1vw;
  color: #0097ff;
}

.fa-angle-right {
  font-size: 5vw;
  color: #ccc;
}
</style> 